package com.maxmlr.music.admin.util;

import com.maxmlr.music.admin.param.TreeParam;

import java.util.*;
import java.util.stream.Collectors;

public class BuildTreeParam {

    public static <T> TreeParam<T> build(List<TreeParam<T>> nodes) {
        List<TreeParam<T>> topNodes = buildList(nodes, "0");

        TreeParam<T> root = new TreeParam<T>();
        if (topNodes.size() == 1) {
            root = topNodes.get(0);
        } else {
            root.setId("-1");
            root.setParentId("");
            root.setHasParent(false);
            root.setHasChildren(true);
            root.setChecked(true);
            root.setChildren(topNodes);
            root.setText("顶级节点");
            Map<String, Object> state = new HashMap<>(16);
            state.put("opened", true);
            root.setState(state);
        }

        return root;
    }

    public static <T> List<TreeParam<T>> buildList(List<TreeParam<T>> nodes, String idParam) {
        if (nodes == null) {
            return null;
        }
        Map<String, List<TreeParam<T>>> listMap = nodes.stream()
                .collect(Collectors.groupingBy(TreeParam::getParentId));
        //顶级节点
        List<TreeParam<T>> topNodes = listMap.get(idParam);
        topNodes.forEach(p -> {
            String id = p.getId();
            Optional<List<TreeParam<T>>> treeParamsOptional = Optional.ofNullable(listMap.get(id));
            if (treeParamsOptional.isPresent()) {
                List<TreeParam<T>> treeParams = treeParamsOptional.get();
                treeParams.forEach(children -> children.setHasParent(true));
                p.setChildren(treeParams);
                p.setHasChildren(true);
            }
        });
        return topNodes;
    }

}